import {
  createRouter,
  createWebHashHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from "vue-router";

import { setBrowserTitle } from "./tools/browser";
import NProgress from "./tools/nprogress";
import { checkLoginStatus } from "./tools/router";

import baseRoutes from "./routes";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "Root",
    redirect: "/base",
    meta: {
      title: "",
      isKeepAlive: false,
    },
  },
  {
    path: "/base",
    name: "Base",
    component: () => import("@/layouts/base/base.vue"),
    redirect: "/dashboard",
    children: [...baseRoutes],
    meta: {
      title: "主页面",
      isKeepAlive: false,
    },
  },

  {
    path: "/login",
    name: "Login",
    component: () => import("@/layouts/login/login.vue"),
    meta: {
      title: "登录页面",
      isKeepAlive: false,
    },
  },

  {
    path: "/logout",
    name: "Logout",
    component: () => import("@/layouts/logout/logout.vue"),
    meta: {
      title: "退出页面",
      isKeepAlive: false,
    },
  },

  {
    path: "/permission",
    name: "Permission",
    component: () => import("@/layouts/permission/permission.vue"),
    meta: {
      title: "无权限页面",
      isKeepAlive: false,
    },
  },

  {
    path: "/404",
    name: "404",
    component: () => import("@/layouts/404/404.vue"),
    meta: {
      title: "404页面",
      isKeepAlive: false,
    },
  },

  {
    // vue2 匹配剩余路径用 "*", vue3 用 "/:pathMatch(.*)",
    path: "/:pathMatch(.*)",
    name: "404",
    component: () => import("@/layouts/404/404.vue"),
    meta: {
      title: "404页面",
      isKeepAlive: false,
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  // 加载所有路由
  routes,
});

/**
 * 进入 router 拦截
 */
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    _from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    // 设置浏览器 title
    setBrowserTitle(to);

    // 开启路由进度条
    NProgress.start();

    // 检查登录状态是否失效，跳转登录页面
    await checkLoginStatus(to, next);

    next();
  }
);

/**
 * 退出 router 拦截
 */
router.afterEach(() => {
  // 关闭路由进度条;
  NProgress.done();
});

export default router;
